package com.hq.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.hq.web.util.FileUploadProcessEntity;

@Controller
public class UploadController { 
	
	
	@RequestMapping("/upload")
	@ResponseBody
	public void addUser(@RequestParam("file") CommonsMultipartFile[] files,HttpServletRequest request){
		
		HttpSession session=request.getSession();
		FileUploadProcessEntity upEntity=new FileUploadProcessEntity();
		session.setAttribute("uploadProcess", upEntity);
		upEntity.setFileItemCount(files.length);
		for(int i = 0;i<files.length;i++){
			upEntity.setFileItem(i+1);
			System.out.println("fileName---------->" + files[i].getOriginalFilename());
		
			if(!files[i].isEmpty()){
				int pre = (int) System.currentTimeMillis();
				try {
					CommonsMultipartFile file=files[i];
					upEntity.setFileItemArys(file.getSize()/128);
					//拿到输出流，同时重命名上传的文件
					FileOutputStream os = new FileOutputStream("D:/" + new Date().getTime() + files[i].getOriginalFilename());
					//拿到上传文件的输入流
					InputStream in = files[i].getInputStream();
					
					//以写字节的方式写文件
					byte [] b=new byte[128];
					int len;
					int proInt=0;
					while((len=in.read(b)) != -1){
						proInt++;
						upEntity.setFileItemAry(proInt);
						session.setAttribute("uploadProcess", upEntity);
						os.write(b);
						//Thread.sleep(100);//为了方便查看进度
					}
					os.flush();
					os.close();
					in.close();
					int finaltime = (int) System.currentTimeMillis();
					System.out.println(finaltime - pre);
					
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("上传出错");
				}
		}
		}
	}
	
	//这种方法上传文件比较快！
	@RequestMapping("/upload2"	)
	@ResponseBody
	public void upload2(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {
		
		//上传进度
		FileUploadProcessEntity upEntity=new FileUploadProcessEntity();
		
		//创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		//判断 request 是否有文件上传,即多部分请求
		if(multipartResolver.isMultipart(request)){
			//转换成多部分request  
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
			
			upEntity.setFileItemCount(multiRequest.getFileMap().size());//文件总数
			
			//取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			int currentItem=1;
			while(iter.hasNext()){
				upEntity.setFileItem(currentItem);
				currentItem++;
				//记录上传过程起始时的时间，用来计算上传时间
				int pre = (int) System.currentTimeMillis();
				//取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				if(file != null){
					upEntity.setFileItemArys(file.getSize());
					//取得当前上传文件的文件名称
					String myFileName = file.getOriginalFilename();
					//如果名称不为“”,说明该文件存在，否则说明该文件不存在
					if(myFileName.trim() !=""){
						System.out.println(myFileName);
						//重命名上传后的文件名
						String fileName = "demoUpload" + file.getOriginalFilename();
						//定义上传路径
						String path = "D:/" + fileName;
						File localFile = new File(path);
						file.transferTo(localFile);
					}
				}
				//记录上传该文件后的时间
				int finaltime = (int) System.currentTimeMillis();
				System.out.println(finaltime - pre);
			}
			
		}
	}
	
	@RequestMapping("/toUpload"	) 
	public String toUpload() {
		
		return "/upload";
	}
	@RequestMapping("/getUploadProcess"	) 
	@ResponseBody
	public JSONObject getUploadProcess(HttpServletRequest request) {
		HttpSession session=request.getSession();
		FileUploadProcessEntity entity=	(FileUploadProcessEntity) session.getAttribute("upload_ps");
		JSONObject resJsonObject=JSONObject.fromObject(entity);
		return resJsonObject;
	}
	@RequestMapping("/getUploadProcess2"	) 
	@ResponseBody
	public JSONObject getUploadProcess2(HttpServletRequest request) {
		HttpSession session=request.getSession();
	    Object status = session.getAttribute("upload_ps");
		JSONObject resJsonObject=JSONObject.fromObject(status);
		return resJsonObject;
	}
	
}
